<template>
  <ul class="list-container">
    <li
      v-for="(item, index) in listItems"
      :key="index"
      class="list-item"
      :class="{ 'active': activeIndex === index }"
      @click="handleClick(index)"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue';

// 定义props，接收列表项数据
const props = defineProps({
  listItems: {
    type: Array,
    required: true,
  },
});

// 定义emits，用于向父组件发射点击事件
const emits = defineEmits(['item-clicked']);

// 用于记录当前激活的列表项索引
const activeIndex = ref(0);

// 点击列表项的处理函数，发射点击事件给父组件，并设置当前点击项为激活状态
const handleClick = (clickedIndex) => {
  emits('item-clicked', clickedIndex);
  activeIndex.value = props.listItems.findIndex((_, index) => index === clickedIndex);
};
</script>

<style scoped>
.list-container {
  list-style-type: none;
  padding: 0;
}

.list-item {
  margin-bottom: 6px;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  border-radius: 4px;
}

.list-item:hover,
.list-item.active {
  background-color: #135369;
}
</style>